package com.woniuxy.client;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户审批流程Flowable客户端
 * 通过 HTTP 调用 flowable-server 的 API
 */
@Slf4j
@Component
public class CustomerFlowableClient {
    
    // 使用网关地址，通过网关访问flowable服务
    private String flowableServiceUrl = "http://localhost:9999/flowable-server";
    
    /**
     * 启动客户审批流程
     * 
     * @param processKey 流程定义Key
     * @param businessKey 业务键（客户ID）
     * @param variables 流程变量
     * @return 流程实例ID
     */
    public String startProcess(String processKey, String businessKey, Map<String, Object> variables) {
        try {
            String url = flowableServiceUrl + "/customer-workflow/process/start";
            
            Map<String, Object> params = new HashMap<>();
            params.put("processDefinitionKey", processKey);
            params.put("businessKey", businessKey);
            params.put("variables", variables);
            
            log.info("启动客户审批流程，URL: {}, 参数: {}", url, JSONUtil.toJsonStr(params));
            
            String response = HttpUtil.createPost(url)
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(params))
                    .execute()
                    .body();
            Map<String, Object> result = JSONUtil.toBean(response, Map.class);
            
            // 检查响应是否成功
            Boolean success = (Boolean) result.get("success");
            if (success != null && success) {
                // 从 data 字段中获取 processInstanceId
                Map<String, Object> data = (Map<String, Object>) result.get("data");
                if (data != null && data.containsKey("processInstanceId")) {
                    String processInstanceId = (String) data.get("processInstanceId");
                    log.info("客户审批流程启动成功，流程实例ID: {}", processInstanceId);
                    return processInstanceId;
                } else {
                    throw new RuntimeException("响应中缺少 processInstanceId");
                }
            } else {
                String message = (String) result.get("message");
                throw new RuntimeException("启动客户审批流程失败: " + (message != null ? message : "未知错误"));
            }
            
        } catch (Exception e) {
            log.error("调用客户审批Flowable服务失败", e);
            throw new RuntimeException("启动客户审批流程失败: " + e.getMessage());
        }
    }
    
    /**
     * 完成任务
     * 
     * @param taskId 任务ID
     * @param variables 流程变量
     */
    public void completeTask(String taskId, Map<String, Object> variables) {
        try {
            String url = flowableServiceUrl + "/customer-workflow/tasks/complete";
            
            Map<String, Object> params = new HashMap<>();
            params.put("taskId", taskId);
            params.put("variables", variables);
            
            log.info("完成客户审批任务，URL: {}, 参数: {}", url, JSONUtil.toJsonStr(params));
            
            String response = HttpUtil.createPost(url)
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(params))
                    .execute()
                    .body();
            log.info("客户审批任务完成成功，响应: {}", response);
            
        } catch (Exception e) {
            log.error("完成客户审批任务失败", e);
            throw new RuntimeException("完成客户审批任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过审批
     * 
     * @param taskId 任务ID
     */
    public void approveTask(String taskId) {
        try {
            String url = flowableServiceUrl + "/customer-workflow/tasks/approve?taskId=" + taskId;
            
            log.info("通过客户审批，URL: {}", url);
            
            String response = HttpUtil.createPost(url)
                    .header("Content-Type", "application/json")
                    .execute()
                    .body();
            log.info("客户审批通过成功，响应: {}", response);
            
        } catch (Exception e) {
            log.error("客户审批通过失败", e);
            throw new RuntimeException("客户审批通过失败: " + e.getMessage());
        }
    }
    
    /**
     * 拒绝审批
     * 
     * @param taskId 任务ID
     * @param reason 拒绝原因
     */
    public void rejectTask(String taskId, String reason) {
        try {
            String url = flowableServiceUrl + "/customer-workflow/tasks/reject?taskId=" + taskId + "&reason=" + reason;
            
            log.info("拒绝客户审批，URL: {}", url);
            
            String response = HttpUtil.createPost(url)
                    .header("Content-Type", "application/json")
                    .execute()
                    .body();
            log.info("客户审批拒绝成功，响应: {}", response);
            
        } catch (Exception e) {
            log.error("客户审批拒绝失败", e);
            throw new RuntimeException("客户审批拒绝失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询待办任务
     * 
     * @param assignee 处理人
     * @return 任务列表
     */
    public String getTasksByAssignee(String assignee) {
        try {
            String url = flowableServiceUrl + "/customer-workflow/tasks/pending?userName=" + assignee;
            
            log.info("查询客户审批待办任务，URL: {}", url);
            
            String response = HttpUtil.get(url);
            log.info("查询客户审批待办任务成功，响应: {}", response);
            
            return response;
            
        } catch (Exception e) {
            log.error("查询客户审批待办任务失败", e);
            throw new RuntimeException("查询客户审批待办任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询流程状态
     * 
     * @param processInstanceId 流程实例ID
     * @return 流程状态信息
     */
    public String getProcessStatus(String processInstanceId) {
        try {
            String url = flowableServiceUrl + "/customer-workflow/process/status?processInstanceId=" + processInstanceId;
            
            log.info("查询客户审批流程状态，URL: {}", url);
            
            String response = HttpUtil.get(url);
            log.info("查询客户审批流程状态成功，响应: {}", response);
            
            return response;
            
        } catch (Exception e) {
            log.error("查询客户审批流程状态失败", e);
            throw new RuntimeException("查询客户审批流程状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询流程步骤
     * 
     * @param processInstanceId 流程实例ID
     * @return 流程步骤信息
     */
    public String getProcessSteps(String processInstanceId) {
        try {
            String url = flowableServiceUrl + "/customer-workflow/process/steps?processInstanceId=" + processInstanceId;
            
            log.info("查询客户审批流程步骤，URL: {}", url);
            
            String response = HttpUtil.get(url);
            log.info("查询客户审批流程步骤成功，响应: {}", response);
            
            return response;
            
        } catch (Exception e) {
            log.error("查询客户审批流程步骤失败", e);
            throw new RuntimeException("查询客户审批流程步骤失败: " + e.getMessage());
        }
    }
}
